//    Openbravo POS is a point of sales application designed for touch screens.
//    Copyright (C) 2008-2009 Openbravo, S.L.
//    http://www.openbravo.com/product/pos
//
//    This file is part of Openbravo POS.
//
//    Openbravo POS is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    Openbravo POS is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with Openbravo POS.  If not, see <http://www.gnu.org/licenses/>.

package com.openbravo.pos.panels;

import cn.ekuma.epos.datalogic.I_DataLogicSales;
import cn.ekuma.swing.dialog.AbstractKeyBoardJDialog;
import com.openbravo.data.basic.BasicException;

import com.openbravo.pos.base.AppLocal;
import com.openbravo.pos.util.RoundUtils;
import com.openbravo.bean.Attribute;
import com.openbravo.bean.AttributeInstInfo;
import com.openbravo.bean.AttributeInstance;
import com.openbravo.bean.AttributeSet;
import com.openbravo.bean.AttributeSetInstance;
import com.openbravo.bean.AttributeValue;
import com.openbravo.bean.ProductAttributeValuePrice;
import e.odbo.data.dao.util.DAOUtils;

import java.awt.Component;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.Window;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.swing.AbstractListModel;
import javax.swing.SwingUtilities;

/**
 *
 * @author adrianromero
 */
public class JProductAttEdit extends AbstractKeyBoardJDialog {

    private List<I_ProductAttEdit> itemslist;
    private String attsetid;

    private double deffPrice;

    private boolean ok;
    
    I_DataLogicSales dlSale;
    
    private AttributeSetInstance attSetInstance;
	private double deffPriceCost;

    /** Creates new form JProductAttEdit 
     * @wbp.parser.constructor*/
    private JProductAttEdit(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
    }

    /** Creates new form JProductAttEdit */
    private JProductAttEdit(java.awt.Dialog parent, boolean modal) {
        super(parent, modal);
    }

    private void init(I_DataLogicSales dlSale) {
    	this.dlSale=dlSale;
        initComponents();
        getRootPane().setDefaultButton(m_jButtonOK);
    }


    public static JProductAttEdit getAttributesEditor(Component parent, I_DataLogicSales dlSale) {

        Window window = SwingUtilities.getWindowAncestor(parent);

        JProductAttEdit myMsg;
        if (window instanceof Frame) {
            myMsg = new JProductAttEdit((Frame) window, true);
        } else {
            myMsg = new JProductAttEdit((Dialog) window, true);
        }
        myMsg.init(dlSale);
        myMsg.applyComponentOrientation(parent.getComponentOrientation());
        return myMsg;
    }

    public void editAttributes(String attsetid, String attsetinstid,String productId) throws BasicException {
    	attSetInstance=null;
        if (attsetid == null) {
            throw new BasicException(AppLocal.getIntString("message.cannotfindattributes"));
        } else {

            this.attsetid = attsetid;     

            this.ok = false;

            // get attsetinst values
            AttributeSet asi =(AttributeSet) dlSale.findByStringId(AttributeSet.class,attsetid);

            if (asi == null) {
                throw new BasicException(AppLocal.getIntString("message.cannotfindattributes"));
            }

            setTitle(asi.getName());

             final List findarrSetInst=dlSale.listByParent(AttributeSetInstance.class,DAOUtils.getParentNode(AttributeSet.class,attsetid));

            jAttrSetInstList.setModel(new AbstractListModel(){
                @Override
                public int getSize() {
                    if(findarrSetInst==null)
                        return 0;
                   return findarrSetInst.size();
                }
                @Override
                public Object getElementAt(int index) {
                    return findarrSetInst.get(index);
                }
            });

            List<AttributeInstInfo> attinstinfo = attsetinstid == null
                    ? dlSale.listAttributeInstInfo(attsetid)
                    : dlSale.listAttributeInstInfo(attsetid, attsetinstid);

            itemslist = new ArrayList<I_ProductAttEdit>();

            for (AttributeInstInfo aii : attinstinfo) {

                I_ProductAttEdit item;

                List<AttributeValue> values = dlSale.list(AttributeValue.class, Attribute.class, aii.getAttid());
                if (values.isEmpty()) {
                    // Does not exist a list of values then a textfield
                    item = new JProductAttEditItem(aii.getAttid(),  aii.getAttname(), aii.getValue(), m_jKeys);
                } else {
                    // Does exist a list with the values
                    item = new JProductAttListItem(aii.getAttid(),  aii.getAttname(), aii.getValue(), values,dlSale,productId);
                }

                itemslist.add(item);
                jPanel2.add(item.getComponent());
            }

            if (itemslist.size() > 0) {
                itemslist.get(0).assignSelection();
                //jAttrSetInstList.setSelectedValue(new AttSetInstInfo(attsetinstid,null), true);
            }
        }
    }

    public boolean isOK() {
        return ok;
    }
    
    public AttributeSetInstance getAttributeSetInstance() {
		return attSetInstance;
	}
    
    @Override
    protected void enterKeyProc() {
        if(m_jButtonOK.isEnabled()){
            m_jButtonOKActionPerformed(null);
        }
    }

    @Override
    protected void escapeKeyProc() {
        dispose();
    }

    @Override
    protected void upKeyProc() {

    }

    @Override
    protected void downKeyProc() {

    }

    public void editAttributes(String attributesetid, String attsetinstid, boolean editAble) throws BasicException {
        editAttributes(attributesetid, attsetinstid,null);
        m_jButtonOK.setEnabled(editAble);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel5 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        m_jButtonOK = new javax.swing.JButton();
        m_jButtonCancel = new javax.swing.JButton();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel6 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jAttrSetInstList = new javax.swing.JList();
        jPanel7 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        m_jKeys = new com.openbravo.editor.JEditorKeys();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel5.setLayout(new java.awt.BorderLayout());

        jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

        m_jButtonOK.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/button_ok.png"))); // NOI18N
        m_jButtonOK.setText(AppLocal.getIntString("Button.OK")); // NOI18N
        m_jButtonOK.setFocusPainted(false);
        m_jButtonOK.setFocusable(false);
        m_jButtonOK.setMargin(new java.awt.Insets(8, 16, 8, 16));
        m_jButtonOK.setRequestFocusEnabled(false);
        m_jButtonOK.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                m_jButtonOKActionPerformed(evt);
            }
        });
        jPanel1.add(m_jButtonOK);

        m_jButtonCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/openbravo/images/button_cancel.png"))); // NOI18N
        m_jButtonCancel.setText(AppLocal.getIntString("Button.Cancel")); // NOI18N
        m_jButtonCancel.setFocusPainted(false);
        m_jButtonCancel.setFocusable(false);
        m_jButtonCancel.setMargin(new java.awt.Insets(8, 16, 8, 16));
        m_jButtonCancel.setRequestFocusEnabled(false);
        m_jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                m_jButtonCancelActionPerformed(evt);
            }
        });
        jPanel1.add(m_jButtonCancel);

        jPanel5.add(jPanel1, java.awt.BorderLayout.SOUTH);

        jPanel6.setLayout(new java.awt.BorderLayout());

        jAttrSetInstList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(jAttrSetInstList);

        jPanel6.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jTabbedPane1.addTab(AppLocal.getIntString("tablabel.jproductattedit.attsetinstlist"), jPanel6); // NOI18N

        jPanel7.setLayout(new java.awt.BorderLayout());

        jPanel2.setLayout(new javax.swing.BoxLayout(jPanel2, javax.swing.BoxLayout.PAGE_AXIS));
        jPanel7.add(jPanel2, java.awt.BorderLayout.NORTH);

        jTabbedPane1.addTab(AppLocal.getIntString("tablabel.jproductattedit.attsetinstedit"), jPanel7); // NOI18N

        jPanel5.add(jTabbedPane1, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel5, java.awt.BorderLayout.CENTER);

        jPanel3.setLayout(new java.awt.BorderLayout());

        jPanel4.setLayout(new javax.swing.BoxLayout(jPanel4, javax.swing.BoxLayout.Y_AXIS));
        jPanel4.add(m_jKeys);

        jPanel3.add(jPanel4, java.awt.BorderLayout.NORTH);

        getContentPane().add(jPanel3, java.awt.BorderLayout.EAST);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-609)/2, (screenSize.height-388)/2, 609, 388);
    }// </editor-fold>

    private void m_jButtonOKActionPerformed(java.awt.event.ActionEvent evt) {
    	deffPrice=0;
    	deffPriceCost=0;
        if(jTabbedPane1.getSelectedIndex()==0){
            attSetInstance=(AttributeSetInstance)jAttrSetInstList.getSelectedValue();
             if(attSetInstance!=null){
                ok = true; 
             }
            dispose();
            return;
        }

        StringBuilder description = new StringBuilder();
        for (I_ProductAttEdit item : itemslist) {
            String value = item.getValue();
            if (value != null && value.length() > 0) {
                if (description.length() > 0) {
                    description.append(", ");
                }
                description.append(value);
                ProductAttributeValuePrice valuePrice=item.getProductAttValuePrice();
                if(valuePrice!=null){
                   deffPrice=RoundUtils.add(deffPrice, valuePrice.getDiffprice());
                   deffPriceCost=RoundUtils.add(deffPriceCost, valuePrice.getDiffPriceCost());
                }
            }
        }
        String id;

        if (description.length() == 0) {
            // No values then id is null
            id = null;
        } else {
            // Some values then an instance should exists.
            try {
                // Exist an attribute set instance with these values for the attributeset selected
                id = dlSale.findAttributeSetInstanceId(attsetid, description.toString());
                if(id!=null)
                	attSetInstance=(AttributeSetInstance) dlSale.findByStringId(AttributeSetInstance.class, id);
            } catch (BasicException ex) {
                // Logger.getLogger(JProductAttEdit.class.getName()).log(Level.SEVERE, null, ex);
                return;
            }


            if (id == null) {
                // No, create a new ATTRIBUTESETINSTANCE and return the ID generated
                // or return null... That means that that product does not exists....
                // Maybe these two modes must be supported one for selection and other for creation....
                id = UUID.randomUUID().toString();
                attSetInstance=new AttributeSetInstance();
                attSetInstance.setId(id);
                attSetInstance.setAttributeSetID(attsetid);
                attSetInstance.setDescription(description.toString());
                attSetInstance.setDiffPrice(deffPrice);
                attSetInstance.setDiffPriceCost(deffPriceCost);
                try {
                	dlSale.insert(attSetInstance);
                	AttributeInstance attrInst;
                    for (I_ProductAttEdit item : itemslist) {
                    	attrInst=new AttributeInstance();
                    	attrInst.setAttributeSetInstanceID(id);
                    	attrInst.setAttributeID(item.getAttribute());
                    	attrInst.setValue(item.getValue());
                    	dlSale.insert(attrInst);
                    }
                } catch (BasicException ex) {
                    // Logger.getLogger(JProductAttEdit.class.getName()).log(Level.SEVERE, null, ex);
                    return;
                }
            }
        }

        ok = true;
        dispose();
    }

    private void m_jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {

        dispose();
    }

    // Variables declaration - do not modify
    private javax.swing.JList jAttrSetInstList;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JButton m_jButtonCancel;
    private javax.swing.JButton m_jButtonOK;
    private com.openbravo.editor.JEditorKeys m_jKeys;
    // End of variables declaration

}
